const app = getApp();
function chooseType(_this, options){
  app.getUserInfo();
  if (!_this.data.attr){
    wx.showToast({ title: '请选择属性', icon: 'none', });
    return false;
  }
  var attrl = Object.keys(_this.data.attr).length;
  var servicedata = _this.data.servicedata
  switch (servicedata.type) {
    case 1:
      if (attrl < 2) {
        wx.showToast({ title: '请选择属性', icon: 'none', });
        return false;
      }
      break;
    case 2:
      if (attrl < 1) {
        wx.showToast({ title: '请选择属性', icon: 'none', });
        return false;
      }
      break;
    case 3:
      if (attrl < 2) {
        wx.showToast({ title: '请选择属性', icon: 'none', });
        return false;
      }
      break;
  }
  if (warranty(_this) == true) {
    wx.setStorage({
      key: 'attr',
      data: Object.values(_this.data.attr).join(','),
    })
    if (options.currentTarget.dataset.way == 1) {
      wx.navigateTo({ url: '/pages/index/devphoto/choose/choose'});
    } else {
      wx.chooseMessageFile({
        count: 9,
        type: 'file',
        // extension: ['docx', 'doc', 'pdf', 'xlsx'],
        success: function (res) {
          wx.showLoading({
            title: "正在上传"
          })
          var docList = new Array()
          app.globalData.i = 0;
          uploadFile(res.tempFiles, docList);
          
        }
      })
    }
  }
}

function uploadFile(tempFiles, docList) {
  wx.uploadFile({
    url: app.globalData.serviceModel.$$prefix + '/user/uploadFile',
    filePath: tempFiles[app.globalData.i].path,
    name: 'file',
    header: { 'token': wx.getStorageSync('token') },
    success: function (res) {
      var data = JSON.parse(res.data)
      docList.push(data.data)
      app.globalData.docList = docList
      app.globalData.i++
      if(app.globalData.i==tempFiles.length){
        wx.navigateTo({ url: '/pages/index/devphoto/settle/settle?orderType=doc' })
      }else{
        uploadFile(tempFiles, docList);
      }
    },
  })
}
function uploadImg(tempFilePaths, _this) {// 上传图片
  wx.showToast({
    icon: "loading",
    title: "正在上传"
  })
  var type = typeof tempFilePaths[0] == 'object' ? 'lt' : 'bd';
  tempFilePaths.forEach(function (val, index) {
    val = type=='lt' ? val.path : val;
    wx.uploadFile({
      url: app.globalData.serviceModel.$$prefix + '/user/uploadImg',
      filePath: val,
      name: 'userImg',
      header: { 'token': wx.getStorageSync('token') },
      success: function (res) {
        var data = JSON.parse(res.data)
        _this.data.imageList.push(data.data)
        _this.setData({ imageList: _this.data.imageList })
      },
    })
  })
}
function getCurrentPageUrl() {
  var pages = getCurrentPages();
  var currPage = pages[pages.length - 1];
  var url = '/' + currPage.__route__;
  var options = currPage.options;

  if (Object.keys(options) != 0) {
    var option = '';
    for (let o in options) {
      option += o + '=' + options[o];
    }
    url = url + '?' + option
  }
  return url
}

function warranty(self) { //用户未授权
  if (app.globalData.authCode === 501) { //用户尚未授权
    wx.showLoading(' ');
    var jumpurl = getCurrentPageUrl();
    wx.setStorage({
      key: 'jumpurl',
      data: jumpurl,
    })
    wx.reLaunch({
      url: '/pages/person/authorize/authorize',
      complete: function () {
        wx.hideLoading()
      }
    })
  }
  return true;
}

function getImgsNum(imgsObj) { //冲印服务获取数量
  var toatlNum = 0;
  imgsObj.forEach(function (img, index) {
    toatlNum += img.num
  });
  return toatlNum;
}
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getAddress(aid, self) { //选择快递，查询默认地址
  var url = 'api/user/getDefaultAddress';
  var data = {
    aid: aid
  };
  app.globalRequest(url, data, function (res) {
    var res = res.data;
    if (res.code == 200) {
      self.setData({
        address: res.data,
      });
    }
  });
}

function jumpstores() { //跳转到门店列表
  wx.getSetting({
    success(res) {
      if (res.authSetting['scope.userLocation'] == false) {
        wx.showToast({
          title: '请授权',
          icon: 'none'
        })
        wx.openSetting()
      } else {
        wx.navigateTo({
          url: '/pages/store/index',
        })
      }
    }
  })
}

function jumpaddress() {
  wx.navigateTo({
    url: '/pages/user/address',
  })
}

function dealAuthorization() {
  var requestUrl = 'api/User/getUserDetailByOpenid';
  app.globalRequest(requestUrl, {}, function (res) {
    if (res.data.code == 200) {
      app.globalData.userInfo = res.data.data
    } else {
      wx.redirectTo({
        url: '/pages/user/authorize'
      })
    }
  });
}


module.exports = {
  uploadImg: uploadImg,
  chooseType: chooseType,
  warranty: warranty,
  formatTime: formatTime,
  dealAuthorization: dealAuthorization,
  jumpaddress: jumpaddress,
  getAddress: getAddress,
  jumpstores: jumpstores,
  uploadFile: uploadFile,
  getImgsNum: getImgsNum
}